package com.jagochan.imchat.module.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.AttributeKey;

import java.util.Optional;

/**
 * 创建ws连接的时候携带token。后端通过token进行认证
 */
public class CustomWebSocketTokenHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest httpRequest = (HttpRequest) msg;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(httpRequest.getUri());
            Optional<String> tokenOptional = Optional.of(urlBuilder)
                    .map(UrlBuilder::getQuery)
                    .map(k -> k.get("token"))
                    .map(CharSequence::toString);
            // 如果token存在，则存到上下文中
            tokenOptional.ifPresent(s -> ctx.channel().attr(AttributeKey.valueOf("token")).set(s));
            // 去掉token参数（否则无法创建ws连接），要创建ws连接必须是【/】，不能是【/?token=xxx】
            httpRequest.setUri(urlBuilder.getPath().toString());
        }
        ctx.fireChannelRead(msg);
    }
}
